package com.cmcc.aregister.ui.activity;

import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.cmcc.aregister.R;
import com.cmcc.aregister.cs.constant.Arguments;
import com.cmcc.aregister.cs.constant.ConfigUtilHelper;
import com.cmcc.aregister.cs.constant.GlobalSetting;
import com.cmcc.aregister.cs.database.DatabaseAdapter;
import com.cmcc.aregister.cs.http.HttpAsyncTask;
import com.cmcc.aregister.cs.model.User;
import com.cmcc.aregister.cs.util.UniqueKey;
import com.cmcc.aregister.cs.util.Utils;

public class MyServiceActivity extends ParentActivity {
	private final String TAG = "MyServiceActivity";
	// ------view------
	private Button homeBtn, editBtn, bookBtn, orderBtn;
	private TextView userNameTxt, userSexTxt, UserPhoneNumberTxt, cardTxt,socialCardTxt, birthTxt;
	boolean isSet = false;
	boolean isLogin = false;
	// ------parameter------
	private User user;
	private DatabaseAdapter mDatabaseAdapter;
	private LinearLayout layout01, layout02;
	private TextView loginWarningTitle;
	private boolean canCheckOtherMsg = false;

	// -----------

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		init(R.layout.p_myservice);
		mHttpManager.setCxt(getParent());
		//一期的处理方式
		/*if(ConfigUtilHelper.getMobile(this).equals("") && !ConfigUtilHelper.isShow){
			gotoLogin();
			ConfigUtilHelper.isShow = true;
			return;
		}*/
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onRestart() {
		super.onRestart();
	}


	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	protected void setupData() {
		mDatabaseAdapter = new DatabaseAdapter(this);
	}

	/*private void isLoginTimeout() {
		mDatabaseAdapter.open_user();
		Cursor c = mDatabaseAdapter.fetchAllUserData();
		if (c != null) {
			c.moveToFirst();
			if (c.getCount() > 0) {
				String date = c.getString(c.getColumnIndex("login_date"));
				String loginDate = new Date(Long.parseLong(date)).toString();
				long dateMillis = System.currentTimeMillis();
				String now = new Date(dateMillis).toString();
				SharedPreferences mSharedPreferences = getSharedPreferences(
						ConfigUtilHelper.INFO_VISIBLE_PREFS,
						Context.MODE_PRIVATE);
				Editor edit = mSharedPreferences.edit();
				if (loginDate.equals(now)) {
					edit.putBoolean(ConfigUtilHelper.IS_LOGIN, true);
				} else {
					edit.putBoolean(ConfigUtilHelper.IS_LOGIN, false);
				}
				edit.commit();
			}
		}
		c.close();
		mDatabaseAdapter.close_user();
	}*/

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		canCheckOtherMsg = false;
		isLogin = ConfigUtilHelper.isLogin(this);
		
		SharedPreferences infoVisiblePre = getSharedPreferences(
				ConfigUtilHelper.INFO_VISIBLE_PREFS, Context.MODE_PRIVATE);
		isSet = infoVisiblePre.getBoolean(ConfigUtilHelper.info_visible_set,
				false);
		
		if (isSet) {
			if (!isLogin) {
				loginWarningTitle.setVisibility(View.VISIBLE);
				layout01.setVisibility(View.GONE);
				layout02.setVisibility(View.GONE);
				cardTxt.setText("");
				socialCardTxt.setText("");
				birthTxt.setText("");
			} else {
				if (ConfigUtilHelper.debug) {
					Log.i(TAG, "----is login---------");
				}
				initUserData();
				loadUserInfo();
				canCheckOtherMsg = true;
			}
		} else {
			if (ConfigUtilHelper.debug) {
				Log.i(TAG, "----1111111---------");
			}
			mDatabaseAdapter.open_user();
			Cursor c = mDatabaseAdapter.fetchAllUserData();
			if (c != null && c.getCount() > 0) {
				initUserData();
				loadUserInfo();
				canCheckOtherMsg = true;
			} else {
				loginWarningTitle.setVisibility(View.VISIBLE);
				layout01.setVisibility(View.GONE);
				layout02.setVisibility(View.GONE);
				cardTxt.setText("");
				socialCardTxt.setText("");
				birthTxt.setText("");
			}
			c.close();
			mDatabaseAdapter.close_user();
		}
	}

	@Override
	protected void setupView() {
		((TextView) findViewById(R.id.title)).setText(R.string.myservice);
		homeBtn = (Button) findViewById(R.id.top_left_image);
		homeBtn.setVisibility(View.VISIBLE);
		homeBtn.setOnClickListener(onClickListener);
		editBtn = (Button) findViewById(R.id.top_right_btn);
		editBtn.setVisibility(View.VISIBLE);
		editBtn.setText(getString(R.string.edit));
		editBtn.setOnClickListener(onClickListener);
		bookBtn = (Button) findViewById(R.id.book_btn);
		bookBtn.setOnClickListener(onClickListener);
		orderBtn = (Button) findViewById(R.id.order_btn);
		orderBtn.setOnClickListener(onClickListener);
		userNameTxt = (TextView) findViewById(R.id.name_txt);
		userSexTxt = (TextView) findViewById(R.id.sex_txt);
		UserPhoneNumberTxt = (TextView) findViewById(R.id.number_txt);
		cardTxt = (TextView) findViewById(R.id.card_txt);
		socialCardTxt = (TextView) findViewById(R.id.social_card_txt);
		birthTxt = (TextView) findViewById(R.id.birth_txt);

		layout01 = (LinearLayout) findViewById(R.id.layout_01);
		layout02 = (LinearLayout) findViewById(R.id.layout_02);
		loginWarningTitle = (TextView) findViewById(R.id.login_warning_title);
	}

	private void loadUserInfo() {
		userNameTxt.setText(user.name);
		userSexTxt.setText(user.sex);
		UserPhoneNumberTxt.setText(user.mobile);
		cardTxt.setText(user.card);
		socialCardTxt.setText(user.social_card);
		birthTxt.setText(user.birth);
	}

	/**
	 * 获取用户信息
	 */
	private HttpAsyncTask sendGetUserInfoTask;
	
	OnClickListener onClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			int id = v.getId();
			switch (id) {
			case R.id.top_left_image:
				gobackHome();
				break;
			case R.id.top_right_btn:
				if (isLogin) {
					//如果本地有身份证信息，说明已经注册过，否则去搜索网络，如果网络数据上有身份证则注册过否则没有注册过
					if(ConfigUtilHelper.isRegister(MyServiceActivity.this)){
						gotoEditUserInfo(true);
					}else{
						Map<String, String> parameterMap = new HashMap<String, String>();
						parameterMap.put("mobile", user.mobile);
						String changeUserInfoUrl = Utils.changeUrl(
								Arguments.SERVER_URL_GET_USER_INFO, parameterMap);
						sendGetUserInfoTask = new HttpAsyncTask(HttpAsyncTask.GET,
								GlobalSetting.XML_GET_USER_INFO, changeUserInfoUrl,
								HttpAsyncTask.CACHE_TYPE_ACTION, false);
						showProgressDialog();
						sendGetUserInfoTask.setUIHandler(sendGetUserInfoTaskHandler);
						mHttpManager.execute(sendGetUserInfoTask);
					}
				} else {
					gotoLogin();
				}
				break;
			case R.id.book_btn:
				if(canCheckOtherMsg){
					gotoAppManagerActivity();
				}else{
					gotoLogin();
				}
				break;
			case R.id.order_btn:
				if(canCheckOtherMsg){
					gotoCustomManagerActivity();
				}else{
					gotoLogin();
				}
				break;
			}
		}
	};

	@SuppressWarnings("unchecked")
	Handler sendGetUserInfoTaskHandler = new Handler() {
		public void handleMessage(Message msg) {
			logger.d("----------sendGetUserInfoTaskHandler----------");
			switch (msg.what) {
			case HttpAsyncTask.TASK_NOTIFY_RETURN_DATA:
				if (msg.obj != null) {
					Map<String, Object> httpMap = (Map<String, Object>) msg.obj;
					User user_new = (User) httpMap.get(Arguments.XML_USER);
					if ("".equals(user_new.card) || "null".equals(user_new.card)) {
						dismissProgressDialog();
						// showInfoDialog(R.string.no_register, true);
						showMsg(R.string.no_register);
						gotoEditUserInfo(false);
					} else {
						Cursor c = mDatabaseAdapter.fetchAllUserData();
						if (c != null) {
							if (ConfigUtilHelper.debug) {
								Log.i(TAG, "--user count----->" + c.getCount());
							}
							if (c.getCount() > 0) {
								mDatabaseAdapter.deleteAllUserData();
								if(user_new.sex == null || user_new.sex.equals("")){
									user_new.sex = "0";
								}
								mDatabaseAdapter.insertUserData(user_new.name, user.mobile, user_new.birth, Integer.parseInt(user_new.sex),
										user_new.card, user_new.social_card, user.login_date);
							} else {
								mDatabaseAdapter.insertUserData(user_new.name, user.mobile, user_new.birth, Integer.parseInt(user_new.sex),
										user_new.card, user_new.social_card, user.login_date);
							}
						}
						c.close();
						mDatabaseAdapter.close_user();
						gotoEditUserInfo(true);
					}
				} else {
					dismissProgressDialog();
					showMsg(R.string.no_register);
					gotoEditUserInfo(false);
				}
				break;
			case HttpAsyncTask.TASK_NOTIFY_CONNECTION_FAIL:
				dismissProgressDialog();
				  showSingleAlertDlg(getString(R.string.notice),
	                    getString(R.string.load_user_info_err_and_no_edit),
	                    getString(R.string.close));
				break;
			}
		}
	};
	
	
	// 回到主界面
	private void gobackHome() {
		Intent intent = new Intent(MyServiceActivity.this, NewIndexActivity.class);
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(intent);
		finish();
	}

	// 跳转到订单管理
	private void gotoAppManagerActivity() {
		Intent intent = new Intent(MyServiceActivity.this,
				AppManagerActivity.class);
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(intent);
	}
	
	// 跳转到我的收藏
	private void gotoCustomManagerActivity() {
		Intent intent = new Intent(MyServiceActivity.this,
				CustomManagerActivity.class);
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(intent);
	}

	// 跳转到登陆界面
	private void gotoLogin() {
		Intent intent = new Intent(MyServiceActivity.this,
				UserLoginActivity.class);
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(intent);
	}

	// 回到个人信息编辑界面
	private void gotoEditUserInfo(boolean isRegister) {
		Intent intent = new Intent(MyServiceActivity.this,
				PersonInfoEditor.class);
		intent.putExtra(Arguments.ACTIVITY_IS_USER, isRegister);
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(intent);
	}

	/*
	 * OnItemClickListener onItemClickListener = new OnItemClickListener() {
	 * 
	 * @Override public void onItemClick(AdapterView<?> arg0, View arg1, int
	 * arg2, long arg3) {
	 * 
	 * } };
	 */

	public void initUserData() {
		loginWarningTitle.setVisibility(View.GONE);
		layout01.setVisibility(View.VISIBLE);
		layout02.setVisibility(View.VISIBLE);
		user = new User();
		mDatabaseAdapter.open_user();
		Cursor c = mDatabaseAdapter.fetchAllUserData();
		if (c != null) {
			c.moveToFirst();
			try{
				if (c.getCount() > 0) {
					user.name = UniqueKey.decodeStr(c.getString(c.getColumnIndex("username")));
					user.mobile = UniqueKey.decodeStr(c.getString(c.getColumnIndex("mobile")));
					user.birth = UniqueKey.decodeStr(c.getString(c.getColumnIndex("birth")));
					int sexId = Integer.valueOf(UniqueKey.decodeStr(c.getString(c.getColumnIndex("sex"))));
					if (sexId == 0) {
						user.sex = context.getString(R.string.man);
					} else {
						user.sex = context.getString(R.string.woman);
					}
					user.card = UniqueKey.decodeStr(c.getString(c.getColumnIndex("card")));
					user.social_card = UniqueKey.decodeStr(c.getString(c.getColumnIndex("social_card")));
					user.login_date = UniqueKey.decodeStr(c.getString(c.getColumnIndex("login_date")));
				}
			}catch (Exception e) {
				// TODO: handle exception
			}
		}
		c.close();
		mDatabaseAdapter.close_user();
	}
}